package com.guchenbo.example.string;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by CreGu on 2016/6/12.
 */
public class TestString {
    private String str = "";
    public static void main(String[] args) throws InterruptedException {
        new TestString().demo();
        String s = "abc";
        // 对象的 + 操作，编译器会使用 StringBuffer#append，然后StringBuffer#toString，生成新的对象
        String s2 = new String("a") + new String("bc");
        // false
        System.out.println(s == s2);

        final String sss1 = "a";
        final String sss2 = "bc";
        String sss3 = sss1 + sss2;
        // sss1 和 sss2 被final引用，编译期间能确定值，认为是常量
        // true
        System.out.println(s == sss3);

        // 常量折叠，编译期间能确定的值
        String s3 = "a" + "bc";
        // true
        System.out.println(s == s3);

        final String s4 = "bc";
        String s5 = "a" + s4;
        // s4 final 常量折叠
        // true
        System.out.println(s == s5);

        String ss1 = "s";
        // new 一个新对象
        String ss2 = new String("s");
        // false
        System.out.println(ss1==ss2);
        // true intern 返回常量池地址
        System.out.println(ss1 == ss2.intern());

        String s11 = new String("1");
        s11.intern();
        String s12 = "1";
        System.out.println(s11 == s12);

        String s13 = new String("1") + new String("1");
        s13.intern();
        String s14 = "11";
        System.out.println(s13 == s14);
    }

    private void demo() throws InterruptedException {
        ExecutorService executor = Executors.newFixedThreadPool(100);
        CountDownLatch countDownLatch = new CountDownLatch(10);
        StringBuilder sb2 = new StringBuilder();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 10; i++) {
            executor.submit(()->{
                for (int j = 0; j < 1000; j++) {
                    str += "0";

                    sb.append("0");
                    sb2.append("0");
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        System.out.println(str.length());
        System.out.println(sb.length());
        System.out.println(sb2.length());

    }
}
